package org.jeecgframework.web.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.mybatis.ext.WiseCoreService;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.json.*;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.service.CbsWarehouseServiceI;
import org.jeecgframework.web.service.CbsWarehouseSlaServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.pojo.base.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;

import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Title: Controller
 * @Description: 物流仓库信息表
 * @author onlineGenerator
 * @date 2018-01-12 17:17:20
 * @version V1.0
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsWarehouseController")
public class CbsWarehouseController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CbsWarehouseController.class);

	@Autowired
	private CbsWarehouseServiceI cbsWarehouseService;
	@Autowired
	private CbsWarehouseSlaServiceI cbsWarehouseSlaServiceI;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ZyCommonService zyCommonService;
	@Autowired
	private WiseCoreService wiseCoreService;
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 物流仓库信息表列表 页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "cbsWarehouse")
	public ModelAndView cbsWarehouse(HttpServletRequest request) {
		return new ModelAndView("com/zybk/cbswarehouse/cbsWarehouseList");
	}
	/**
	 * 选择仓库
	 */
	@RequestMapping(params = "zyChooseWa")
	public ModelAndView zyChooseWa(HttpServletRequest request, HttpSession session){
		String logistics = request.getParameter("logistics");
		System.out.println(logistics);
		session.setAttribute("logistics",logistics);
		return new ModelAndView("com/zybk/cbswarehouse/cbsWarehouseofChoose");
	}
	/**
	 * 签收时选择仓库
	 */
	@RequestMapping(params = "zyChooseWa2")
	public ModelAndView zyChooseWa2(HttpServletRequest request){
		return new ModelAndView("com/zybk/cbswarehouse/cbsWarehouseofChoose2");
	}
	/**
	 * 选择仓库页面
	 */
	@RequestMapping(params = "datagridOfzyChooseWa")
	public void datagridOfzyChooseWa(CbsWarehouseEntity cbsWarehouse, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

		Map param = new HashMap<>();

		for (Object key : request.getParameterMap().keySet()) {
			if ((String[]) request.getParameterMap().get(key) != null) {
				for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
					if (((String[]) request.getParameterMap().get(key))[i] != null) {
						param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
					}
				}
			}
		}
		String logistics = (String)request.getSession().getAttribute("logistics");
		param.put("logistics",logistics);
		param.put("isClose","0");
		wiseCoreService.selectDataGrid("chooseWarehouserDatagrid", param, dataGrid);
		TagUtil.datagrid(response, dataGrid);
	}
	/**
	 * 物流仓库信息表列表 页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goChooseCity")
	public ModelAndView goChooseCity(HttpServletRequest request,String id) {
		List<TreeBa> trees = recursiveTree(id);
		String s = JSON.toJSONString(trees);
		String logistics = request.getParameter("logistics");
		String name = request.getParameter("name");
		request.setAttribute("logistics",logistics);
		request.setAttribute("name",name);
		request.setAttribute("trees",s);
		return new ModelAndView("com/zybk/cbswarehouse/tree");
	}
	@RequestMapping(params = "getCityByIds")
	@ResponseBody
	public AjaxJson getCityByIds(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		try {
			String id = request.getParameter("ids");
			String ids = id.trim();
//			String ids = replaceBlank(id);
//////			String ids = repaceWhiteSapce(id1);
////			String ids = id1.replaceAll(" +", " ");
//			String str = ids.replaceAll("\\s*", "");
//			System.out.println(str);
			StringBuffer stringBuffer = new StringBuffer();
			String[] split = ids.split(" ");
			for (int i=0;i<split.length;i++){
				stringBuffer.append(split[i]).append(",");
			}
			System.out.println(stringBuffer.toString());
			String spilt = spilt(stringBuffer.toString());
			System.out.println(spilt);
			List<Map<String, Object>> territoryList = systemService.findForJdbc("select t.id,t.territoryname from t_s_territory t where territorylevel = 2 and territoryname in (" + spilt + ")");
			ajaxJson.setObj(territoryList);
			ajaxJson.setSuccess(true);
		}catch (Exception e){
			ajaxJson.setSuccess(false);
			e.getMessage();
		}
		return ajaxJson;
	}
	//去掉\t
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
	//多个空格替换成一个空格
	public static String repaceWhiteSapce(String original){
		        StringBuilder sb = new StringBuilder();
		        boolean isFirstSpace = false;//标记是否是第一个空格

		 //        original = original.trim();//如果考虑开头和结尾有空格的情形

		        char c;
		        for(int i = 0; i < original.length(); i++){
			             c = original.charAt(i);
			             if(c == ' ' || c == '\t')//遇到空格字符时,先判断是不是第一个空格字符
				            {
				                 if(!isFirstSpace)
					                    {
					                      sb.append(c);
				                         isFirstSpace = true;
				                    }
				            }
			             else{//遇到非空格字符时
				                sb.append(c);
			                isFirstSpace = false;
				           }
			       }
	        return sb.toString();
	    }
	/**
	 * 关闭仓库跳转界面
	 * @return
	 */
	@RequestMapping(params = "goCloseWare")
	public ModelAndView goCloseWare(HttpServletRequest request){
//		StringUtil.isEmpty()
		String id =  request.getParameter("id");
		request.setAttribute("id",id);
		return new ModelAndView("com/zybk/cbswarehouse/closeWare");
	}
	@RequestMapping(params = "goChooseCity2")
	public ModelAndView goChooseCity2(HttpServletRequest request,String id) {
		List<TreeBa> trees = recursiveTree(id);
		String s = JSON.toJSONString(trees);
		String logistics = request.getParameter("logistics");
		String name = request.getParameter("name");
		request.setAttribute("logistics",logistics);
		request.setAttribute("name",name);

		request.setAttribute("trees",s);
		return new ModelAndView("com/zybk/cbswarehouse/chooseCitySLA2");
	}
	@RequestMapping(params = "goChooseCity4")
	public ModelAndView goChooseCity4(HttpServletRequest request,String id) {
		List<TreeBa> trees = recursiveTree(id);
		String s = JSON.toJSONString(trees);
		String logistics = request.getParameter("logistics");
		String name = request.getParameter("name");
		request.setAttribute("logistics",logistics);
		request.setAttribute("name",name);

		request.setAttribute("trees",s);
		return new ModelAndView("com/zybk/cbswarehouse/chooseCitySLA4");
	}
	@RequestMapping(params = "goChooseCity3")
	public ModelAndView goChooseCity3(HttpServletRequest request,String id) {
		List<TreeBa> trees = recursiveTree(id);
		String s = JSON.toJSONString(trees);
		String logistics = request.getParameter("logistics");
		String name = request.getParameter("name");
		request.setAttribute("logistics",logistics);
		request.setAttribute("name",name);

		request.setAttribute("trees",s);
		return new ModelAndView("com/zybk/cbswarehouse/chooseCitySLA3");
	}
	@RequestMapping(params = "recursiveTree")
	public List<TreeBa> recursiveTree(String id){
		List<TSTerritory> territoryLevel = systemService.findByProperty(TSTerritory.class, "territoryLevel", (short) 1);
		TSTerritory t = null;
		List<TreeBa> list = new ArrayList<>();
		for (int i=0;i<territoryLevel.size();i++){
			TSTerritory tsTerritory = territoryLevel.get(i);
//			String hql = "from TSTerritory where territoryCode like'"+tsTerritory.getTerritoryCode()+"%' and territoryLevel = 2 limit 1";
//			t = zyCommonService.singleResult(hql);
			List<Object> listbySql =  systemService.findListbySql("select * from t_s_territory where territoryCode like '" + tsTerritory.getTerritoryCode() + "%' and territorylevel = 2 ");
			List<TSTerritory> byQueryString = systemService.findByQueryString("from TSTerritory where territoryCode like'" + tsTerritory.getTerritoryCode() + "%' and territoryLevel = 2 ");
			//	System.out.println(byQueryString);
			TreeBa tree = new TreeBa();
			tree.setId(tsTerritory.getId());
			tree.setName(tsTerritory.getTerritoryName());
			for (TSTerritory t1:byQueryString) {
				ZTree tree1 = new ZTree();
				tree1.setId(t1.getId());
				tree1.setName(t1.getTerritoryName());
				tree.getChildren().add(tree1);
			}
			list.add(tree);
		}

		return list;
	}
	/**
	 * 物流仓库列表界面
	 */
	@RequestMapping(params = "dataGridList")
	public void  dataGridList(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid){
		Map param = new HashMap<>();

		for (Object key : request.getParameterMap().keySet()) {
			if ((String[]) request.getParameterMap().get(key) != null) {
				for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
					if (((String[]) request.getParameterMap().get(key))[i] != null) {
						param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
					}
				}
			}
		}

		if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("territoryname")))) {
			String territoryname = oConvertUtils.getString(param.get("territoryname"));
			TSTerritory tsTerritory = systemService.singleResult("from TSTerritory where territoryName='"+territoryname+"' and territoryLevel = 2");
			param.put("territoryname", tsTerritory.getId());
		}

		wiseCoreService.selectDataGrid("selectWarehouserDatagrid", param, dataGrid);
		TagUtil.datagrid(response, dataGrid);
	}
	/**
	 * easyui AJAX请求数据
	 *
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(CbsWarehouseEntity cbsWarehouse, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {

		CriteriaQuery cq = new CriteriaQuery(CbsWarehouseEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsWarehouse, request.getParameterMap());
		try{
			//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.cbsWarehouseService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 物流仓库信息表新增页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(CbsWarehouseEntity cbsWarehouse, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsWarehouse.getId())) {
			cbsWarehouse = cbsWarehouseService.getEntity(CbsWarehouseEntity.class, cbsWarehouse.getId());
			req.setAttribute("cbsWarehousePage", cbsWarehouse);

		}
		List<Map<String, Object>> tsDeparts = systemService.findForJdbc("select id,departname from t_s_depart where org_type='logistics' and logic_delete = '0'");
		req.setAttribute("tsDeparts",tsDeparts);
		return new ModelAndView("com/zybk/cbswarehouse/cbsWarehouse-add");
	}
	@ResponseBody
	@RequestMapping(params = "getProvince")
	public  AjaxJson  getPerson(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
//        message = "查询成功";

		List<TSTerritory> territoryList = null;
		//获取巴可内部负责人
		territoryList = systemService.findHql("from TSTerritory  where  territorylevel = '1'");
		ajaxJson.setObj(territoryList);
		return ajaxJson;
	}
	@ResponseBody
	@RequestMapping(params = "getLogistics")
	public AjaxJson getLogistics(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		try {
			List<TSDepart> tsDeparts = null;
			tsDeparts = systemService.findHql("from TSDepart  where orgType = 'logistics' and logicDelete = '0'");
			ajaxJson.setObj(tsDeparts);
		}catch (Exception e){
			e.getMessage();
		}
		return ajaxJson;
	}
	@ResponseBody
	@RequestMapping(params = "getCity")
	public  AjaxJson  getCity(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		String code  = request.getParameter("code");
		List<TSTerritory> territoryList = null;
		//获取巴可内部负责人
		territoryList = systemService.findHql("from TSTerritory  where  territorylevel = '2' and territoryCode like '"+code+"%'");
		ajaxJson.setObj(territoryList);
		return ajaxJson;
	}
	/**
	 * 添加物流仓库信息表
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(CbsWarehouseEntity cbsWarehouse, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		String name = request.getParameter("name");
		String code = request.getParameter("code");
		String province = request.getParameter("province");
		String logistics = request.getParameter("logistics");
		String city = request.getParameter("city");
		String s = null;
		String cityId = request.getParameter("cityId");
		String cityId2 = request.getParameter("cityId2");
		String cityId3 = request.getParameter("cityId3");
		String cityId4 = request.getParameter("cityId4");
		String name1 = request.getParameter("t1");
		String name2 = request.getParameter("t2");
		String name3 = request.getParameter("t3");
		String name4 = request.getParameter("t4");
		String endCity = "" ;
		if (name1!=null){
			endCity+= " "+name1;
		}
		if (name2!=null){
			endCity+= " "+name2;
		}
		if (name3!=null){
			endCity+= " "+name3;
		}
		if (name4!=null){
			endCity+=" "+name4;
		}
		TSTerritory t = null;
		TSTerritory t2 = new TSTerritory();
		CbsWarehouseEntity CbsWarehouseEntity2 = null;
		if (null!=province){
			String hql = "FROM TSTerritory where territoryCode= '"+province+"' ";
			t = zyCommonService.singleResult(hql);
		}
		t2.setId(city);
		message = "物流仓库信息表添加成功";
		try{
			cbsWarehouse.setSheng(t);
			cbsWarehouse.setShi(t2);
			cbsWarehouse.setIsClose("0");

			cbsWarehouseService.save(cbsWarehouse);
			String id = null;
			Map<String, Object> fileLogMap = systemService.findOneForJdbc ( "select s.id from cbs_warehouse s where code = '"+code+"' ORDER BY s.create_date DESC LIMIT 1 ");
			if(fileLogMap != null){
				id = fileLogMap.get("id").toString();
			}

			String s1 = null;

			String s2 = null;

			String s3 = null;
			if (cityId==""&&cityId2==""&&cityId3==""&&cityId4==""){
				CbsWarehouseEntity cbsWarehouseEntity = new CbsWarehouseEntity();
				CbsWarehouseSlaEntity cbsWarehouseSlaEntity = getCbsWarehouseSlaEntity();
				cbsWarehouseEntity.setId(id);
				cbsWarehouseSlaEntity.setCbsWarehouseId(cbsWarehouseEntity);
				cbsWarehouseSlaEntity.setShi(null);
				cbsWarehouseSlaEntity.setSlaType(null);
				cbsWarehouseSlaServiceI.save(cbsWarehouseSlaEntity);
			}
			if (cityId!=null && cityId!="" ){
				// TODO
				s = cityId.substring(0,cityId.length()-1);
				for(String cId:s.split(",")){
					addWarehouseSla(id,cId,"1");

				}


			}
			if (cityId2!=null && cityId2!=""){
				s1 = cityId2.substring(0,cityId2.length()-1);
				for(String cId:s1.split(",")){
					addWarehouseSla(id,cId,"2");
				}


			}
			if (cityId3!=null && cityId3!=""){
				s2 = cityId3.substring(0,cityId3.length()-1);
				for(String cId:s2.split(",")){
					addWarehouseSla(id,cId,"3");
				}

			}
			if (cityId4!=null && cityId4!=""){
				s3 = cityId4.substring(0,cityId4.length()-1);
				for(String cId:s3.split(",")){
					addWarehouseSla(id,cId,"4");
				}

			}
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "物流仓库信息表添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	public CbsWarehouseSlaEntity getCbsWarehouseSlaEntity(){
		CbsWarehouseSlaEntity cbsWarehouseSlaEntity = new CbsWarehouseSlaEntity();
		return cbsWarehouseSlaEntity;
	}
	@ResponseBody
	@RequestMapping(params = "ifExist")
	public AjaxJson ifExist(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		try {
			String name = request.getParameter("name");
			CbsWarehouseEntity cbsWarehouseEntity = systemService.singleResult("from CbsWarehouseEntity where name = '"+name+"'");
			if (cbsWarehouseEntity!=null){
				ajaxJson.setSuccess(false);
			}else {
				ajaxJson.setSuccess(true);
			}
		}catch (Exception e){
			e.getMessage();
		}
		return ajaxJson;
	}
	/**
	 * 物流仓库信息表编辑页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(CbsWarehouseEntity cbsWarehouse, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsWarehouse.getId())) {
			cbsWarehouse = cbsWarehouseService.getEntity(CbsWarehouseEntity.class, cbsWarehouse.getId());
			req.setAttribute("cbsWarehousePage", cbsWarehouse);
			List<CbsWarehouseSlaEntity> cb = systemService.findByQueryString("from CbsWarehouseSlaEntity where cbsWarehouseId = '" + cbsWarehouse.getId() + "'");
			List<TSTerritory> territoryList = new ArrayList<TSTerritory>();
			List<TSTerritory> territoryList2 = new ArrayList<TSTerritory>();
			List<TSTerritory> territoryList3 = new ArrayList<TSTerritory>();
			List<TSTerritory> territoryList4 = new ArrayList<TSTerritory>();
			StringBuffer stringBuffer = new StringBuffer();
			StringBuffer stringBuffer2 = new StringBuffer();
			StringBuffer stringBuffer3 = new StringBuffer();
			StringBuffer stringBuffer4 = new StringBuffer();

			for (int i=0;i<cb.size();i++){

				CbsWarehouseSlaEntity cbsWarehouseSlaEntity = cb.get(i);
				if ("1".equals(cbsWarehouseSlaEntity.getSlaType())){
					if (cbsWarehouseSlaEntity.getShi()!=null){
						String spilt = spilt(cbsWarehouseSlaEntity.getShi());
						System.out.println(spilt);
						List<TSTerritory> byQueryString = systemService.findByQueryString("from TSTerritory where id = " + spilt + "");
						stringBuffer.append(cbsWarehouseSlaEntity.getId()+",");
						territoryList.addAll(byQueryString);
					}

				}else if ("2".equals(cbsWarehouseSlaEntity.getSlaType())){
					if (cbsWarehouseSlaEntity.getShi()!=null){
						String spilt = spilt(cbsWarehouseSlaEntity.getShi());
						List<TSTerritory> byQueryString = systemService.findByQueryString("from TSTerritory where id = " + spilt + "");
						territoryList2.addAll(byQueryString);
						stringBuffer2.append(cbsWarehouseSlaEntity.getId()+",");
					}

				}else if ("3".equals(cbsWarehouseSlaEntity.getSlaType())){
					if (cbsWarehouseSlaEntity.getShi()!=null){
						String spilt = spilt(cbsWarehouseSlaEntity.getShi());
						List<TSTerritory> byQueryString = systemService.findByQueryString("from TSTerritory where id = " + spilt + "");
						territoryList3.addAll(byQueryString);
						stringBuffer3.append(cbsWarehouseSlaEntity.getId()+",");
					}

				}else if ("4".equals(cbsWarehouseSlaEntity.getSlaType())){
					if (cbsWarehouseSlaEntity.getShi()!=null){
						String spilt = spilt(cbsWarehouseSlaEntity.getShi());
						List<TSTerritory> byQueryString = systemService.findByQueryString("from TSTerritory where id = " + spilt + "");
						territoryList4.addAll(byQueryString);
						stringBuffer4.append(cbsWarehouseSlaEntity.getId()+",");
					}

				}

			}
			if (territoryList!=null&&territoryList.size()>0){
				StringBuffer sd = new StringBuffer();
				for (int i =0;i<territoryList.size();i++){
					sd.append(territoryList.get(i).getTerritoryName()).append(" ");
					System.out.println(sd.toString());
				}
				req.setAttribute("slaOne",sd.toString().trim());
			}
			if (territoryList2!=null&&territoryList2.size()>0){
				StringBuffer sd = new StringBuffer();
				for (int i =0;i<territoryList2.size();i++){
					sd.append(territoryList2.get(i).getTerritoryName()).append(" ");
					System.out.println(sd.toString());
				}
				req.setAttribute("slaTwo",sd.toString().trim());
			}
			if (territoryList3!=null&&territoryList3.size()>0){
				StringBuffer sd = new StringBuffer();
				for (int i =0;i<territoryList3.size();i++){
					sd.append(territoryList3.get(i).getTerritoryName()).append(" ");
					System.out.println(sd.toString());
				}
				req.setAttribute("slaThree",sd.toString().trim());
			}
			if (territoryList4!=null&&territoryList4.size()>0){
				StringBuffer sd = new StringBuffer();
				for (int i =0;i<territoryList4.size();i++){
					sd.append(territoryList4.get(i).getTerritoryName()).append(" ");
					System.out.println(sd.toString());
				}
				req.setAttribute("slaFour",sd.toString().trim());
			}
			if (stringBuffer!=null&&!new String(stringBuffer).equals("")){
				String substring = stringBuffer.substring(0, stringBuffer.length() - 1);
				System.out.println(substring);
				req.setAttribute("slaOneId",substring);
			}
			if (stringBuffer2!=null&&!new String(stringBuffer2).equals("")){
				String substring = stringBuffer2.substring(0, stringBuffer2.length() - 1);
				System.out.println(substring);
				req.setAttribute("slaTwoId",substring);
			}
			if (stringBuffer3!=null&&!new String(stringBuffer3).equals("")){
				String substring = stringBuffer3.substring(0, stringBuffer3.length() - 1);
				System.out.println(substring);
				req.setAttribute("slaThreeId",substring);
			}
			if (stringBuffer4!=null&&!new String(stringBuffer4).equals("")){
				String substring = stringBuffer4.substring(0, stringBuffer4.length() - 1);
				System.out.println(substring);
				req.setAttribute("slaFourId",substring);
			}

		}
		return new ModelAndView("com/zybk/cbswarehouse/cbsWarehouse-update");
	}
	/**
	 * 查看
	 */
	@RequestMapping(params = "goLook")
	public ModelAndView goLook(CbsWarehouseEntity cbsWarehouse, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsWarehouse.getId())) {
			cbsWarehouse = cbsWarehouseService.getEntity(CbsWarehouseEntity.class, cbsWarehouse.getId());
			req.setAttribute("cbsWarehousePage", cbsWarehouse);
			List<CbsWarehouseSlaEntity> cb = systemService.findByQueryString("from CbsWarehouseSlaEntity where cbsWarehouseId = '" + cbsWarehouse.getId() + "'");
			List<TSTerritory> territoryList = new ArrayList<TSTerritory>();
			List<TSTerritory> territoryList2 = new ArrayList<TSTerritory>();
			List<TSTerritory> territoryList3 = new ArrayList<TSTerritory>();
			List<TSTerritory> territoryList4 = new ArrayList<TSTerritory>();
			StringBuffer stringBuffer = new StringBuffer();
			StringBuffer stringBuffer2 = new StringBuffer();
			StringBuffer stringBuffer3 = new StringBuffer();
			StringBuffer stringBuffer4 = new StringBuffer();
			for (int i=0;i<cb.size();i++){
				CbsWarehouseSlaEntity cbsWarehouseSlaEntity = cb.get(i);
				if ("1".equals(cbsWarehouseSlaEntity.getSlaType())){
					String spilt = spilt(cbsWarehouseSlaEntity.getShi());
					System.out.println(spilt);
					List<TSTerritory> byQueryString = systemService.findByQueryString("from TSTerritory where id = " + spilt + "");
					stringBuffer.append(cbsWarehouseSlaEntity.getId()+",");
					territoryList.addAll(byQueryString);
				}else if ("2".equals(cbsWarehouseSlaEntity.getSlaType())){
					String spilt = spilt(cbsWarehouseSlaEntity.getShi());
					List<TSTerritory> byQueryString = systemService.findByQueryString("from TSTerritory where id = " + spilt + "");
					territoryList2.addAll(byQueryString);
					stringBuffer2.append(cbsWarehouseSlaEntity.getId()+",");
				}else if ("3".equals(cbsWarehouseSlaEntity.getSlaType())){
					String spilt = spilt(cbsWarehouseSlaEntity.getShi());
					List<TSTerritory> byQueryString = systemService.findByQueryString("from TSTerritory where id = " + spilt + "");
					territoryList3.addAll(byQueryString);
					stringBuffer3.append(cbsWarehouseSlaEntity.getId()+",");
				}else if ("4".equals(cbsWarehouseSlaEntity.getSlaType())){
					String spilt = spilt(cbsWarehouseSlaEntity.getShi());
					List<TSTerritory> byQueryString = systemService.findByQueryString("from TSTerritory where id = " + spilt + "");
					territoryList4.addAll(byQueryString);
					stringBuffer4.append(cbsWarehouseSlaEntity.getId()+",");
				}

			}
			if (territoryList!=null&&territoryList.size()>0){
				req.setAttribute("slaOne",territoryList);
			}
			if (territoryList2!=null&&territoryList2.size()>0){
				req.setAttribute("slaTwo",territoryList2);
			}
			if (territoryList3!=null&&territoryList3.size()>0){
				req.setAttribute("slaThree",territoryList3);
			}
			if (territoryList4!=null&&territoryList4.size()>0){
				req.setAttribute("slaFour",territoryList4);
			}
			if (stringBuffer!=null&&!new String(stringBuffer).equals("")){
				String substring = stringBuffer.substring(0, stringBuffer.length() - 1);
				System.out.println(substring);
				req.setAttribute("slaOneId",substring);
			}
			if (stringBuffer2!=null&&!new String(stringBuffer2).equals("")){
				String substring = stringBuffer2.substring(0, stringBuffer2.length() - 1);
				System.out.println(substring);
				req.setAttribute("slaTwoId",substring);
			}
			if (stringBuffer3!=null&&!new String(stringBuffer3).equals("")){
				String substring = stringBuffer3.substring(0, stringBuffer3.length() - 1);
				System.out.println(substring);
				req.setAttribute("slaThreeId",substring);
			}
			if (stringBuffer4!=null&&!new String(stringBuffer4).equals("")){
				String substring = stringBuffer4.substring(0, stringBuffer4.length() - 1);
				System.out.println(substring);
				req.setAttribute("slaFourId",substring);
			}
		}
		return new ModelAndView("com/zybk/cbswarehouse/cbsWarehouse-look");
	}
	public String spilt(String str) {
		StringBuffer sb = new StringBuffer();
		String[] temp = str.split(",");
		for (int i = 0; i < temp.length; i++) {
			if (!"".equals(temp[i]) && temp[i] != null)
				sb.append("'" + temp[i] + "',");
		}
		String result = sb.toString();
		String tp = result.substring(result.length() - 1, result.length());
		if (",".equals(tp))
			return result.substring(0, result.length() - 1);
		else
			return result;
	}
	/**
	 * 更新物流仓库信息表
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(CbsWarehouseEntity cbsWarehouse, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String code = request.getParameter("code");
		String province = request.getParameter("province");
		String logistics = request.getParameter("logistics");
		String city = request.getParameter("city");
		String cityId = request.getParameter("cityId");
		String cityId2 = request.getParameter("cityId2");
		String cityId3 = request.getParameter("cityId3");
		String cityId4 = request.getParameter("cityId4");
		String slaOneId = request.getParameter("slaOneId");
		String slaTwoId = request.getParameter("slaTwoId");
		String slaThreeId = request.getParameter("slaThreeId");
		String slaFourId = request.getParameter("slaFourId");
		String name1 = request.getParameter("t1");
		String name2 = request.getParameter("t2");
		String name3 = request.getParameter("t3");
		String name4 = request.getParameter("t4");
		String address = request.getParameter("address");
		String endCity = "" ;
		if (name1!=null){
			endCity+= " "+name1;
		}
		if (name2!=null){
			endCity+= " "+name2;
		}
		if (name3!=null){
			endCity+= " "+name3;
		}
		if (name4!=null){
			endCity+=" "+name4;
		}
		TSTerritory tsTerritory = null;
		TSTerritory t2 = new TSTerritory();
		if (null!=province){
			String hql = "FROM TSTerritory where territoryCode= '"+province+"' ";
			tsTerritory = zyCommonService.singleResult(hql);
		}
		t2.setId(city);
		message = "物流仓库信息表更新成功";

		CbsWarehouseEntity t = cbsWarehouseService.get(CbsWarehouseEntity.class, cbsWarehouse.getId());
		CbsWarehouseSlaEntity cbsWarehouseSlaEntity = systemService.singleResult("from CbsWarehouseSlaEntity where cbsWarehouseId.id='"+cbsWarehouse.getId()+"' and sla_type is NULL");
		if (cbsWarehouseSlaEntity!=null){
			systemService.delete(cbsWarehouseSlaEntity);
		}
		try {
			t.setSheng(tsTerritory);
			t.setShi(t2);
			MyBeanUtils.copyBeanNotNull2Bean(cbsWarehouse, t);
			cbsWarehouseService.saveOrUpdate(t);
			String s1 = null;
			String s2 = null;
			String s3 = null;
			String s = null;
			CbsWarehouseSlaEntity cbsWarehouseSlaEntity2 = new CbsWarehouseSlaEntity();
			CbsWarehouseSlaEntity cbsWarehouseSlaEntity3 = new CbsWarehouseSlaEntity();
			CbsWarehouseSlaEntity cbsWarehouseSlaEntity4 = new CbsWarehouseSlaEntity();
			if (slaOneId!=null&&slaOneId!="") {

				if (cityId != "") {
					for (String sid : slaOneId.split(",")) {
						systemService.updateBySqlString("delete from cbs_warehouse_sla where id = '" + sid + "'");
					}
					s = cityId.substring(0, cityId.length() - 1);
					for (String cId : s.split(",")) {
						addWarehouseSla(id, cId, "1");
					}

				}

			}
			if (slaTwoId!=null&&slaTwoId!=""){

				if (cityId2!=""){
					for(String sid:slaTwoId.split(",")){
						systemService.updateBySqlString("delete from cbs_warehouse_sla where id = '"+sid+"'");
					}
					s2 = cityId2.substring(0,cityId2.length()-1);
					for(String cId:s2.split(",")){
						addWarehouseSla(id,cId,"2");
					}

				}

			}

			if (slaThreeId!=null&&slaThreeId!=""){

				if (cityId3!=""){
					for(String sid:slaThreeId.split(",")){
						systemService.updateBySqlString("delete from cbs_warehouse_sla where id = '"+sid+"'");

					}
					s3 = cityId3.substring(0,cityId3.length()-1);
					for(String cId:s3.split(",")){
						addWarehouseSla(id,cId,"3");
					}
				}

			}
			else{
			}
			if (slaFourId!=null&&slaFourId!=""){

				if (cityId4!=""){
					for(String sid:slaFourId.split(",")){
						systemService.updateBySqlString("delete from cbs_warehouse_sla where id = '"+sid+"'");
					}
					s1 = cityId4.substring(0,cityId4.length()-1);
					for(String cId:s1.split(",")){
						addWarehouseSla(id,cId,"4");
					}
				}
			}
			if (slaOneId==""&&cityId!=""){
				String substring = cityId.substring(0, cityId.length() - 1);
				for(String cId:substring.split(",")){
					addWarehouseSla(id,cId,"1");
				}


			}
			if (slaTwoId==""&&cityId2!=""){
				String substring = cityId2.substring(0, cityId2.length() - 1);
				for(String cId:substring.split(",")){
					addWarehouseSla(id,cId,"2");
				}
//				systemService.updateBySqlString("update cbs_warehouse_sla set shi = NULL where cbs_warehouse_id = '"+cbsWarehouse.getId()+"' and sla_type = '2'");

			}
			if (slaThreeId==""&&cityId3!=""){
				String substring = cityId3.substring(0, cityId3.length() - 1);
				for(String cId:substring.split(",")){
					addWarehouseSla(id,cId,"3");
				}
//				systemService.updateBySqlString("update cbs_warehouse_sla set shi = NULL where cbs_warehouse_id = '"+cbsWarehouse.getId()+"' and sla_type = '3'");

			}
			if (slaFourId==""&&cityId4!=""){
				String substring = cityId4.substring(0, cityId4.length() - 1);
				for(String cId:substring.split(",")){
					addWarehouseSla(id,cId,"4");
				}
			}
			if (cityId==""&&slaOneId==""){
				systemService.updateBySqlString("update cbs_warehouse_sla set shi = NULL where cbs_warehouse_id = '"+cbsWarehouse.getId()+"' and sla_type = '1'");
			}
			if (cityId2==""&&slaTwoId==""){
				systemService.updateBySqlString("update cbs_warehouse_sla set shi = NULL where cbs_warehouse_id = '"+cbsWarehouse.getId()+"' and sla_type = '2'");
			}
			if (cityId3==""&&slaThreeId==""){
				systemService.updateBySqlString("update cbs_warehouse_sla set shi = NULL where cbs_warehouse_id = '"+cbsWarehouse.getId()+"' and sla_type = '3'");
			}
			if (cityId4==""&&slaFourId==""){
				systemService.updateBySqlString("update cbs_warehouse_sla set shi = NULL where cbs_warehouse_id = '"+cbsWarehouse.getId()+"' and sla_type = '4'");
			}
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e ) {
			e.printStackTrace();
			message = "物流仓库信息表更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	//临时添加仓库
	public void addWarehouseSla(String id,String cid,String slaType){
		CbsWarehouseEntity cbsWarehouseEntity = new CbsWarehouseEntity();
		CbsWarehouseSlaEntity cbsWarehouseSlaEntity = getCbsWarehouseSlaEntity();
		cbsWarehouseEntity.setId(id);
		cbsWarehouseSlaEntity.setCbsWarehouseId(cbsWarehouseEntity);
		cbsWarehouseSlaEntity.setShi(cid);
		cbsWarehouseSlaEntity.setSlaType(slaType);
		cbsWarehouseSlaEntity.setIsPriority("0");
		cbsWarehouseSlaServiceI.save(cbsWarehouseSlaEntity);
	}
	/**
	 * 关闭仓库
	 *
	 * @return
	 */
	@RequestMapping(params = "closeWare")
	@ResponseBody
	public AjaxJson closeWare(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		Map map = new HashMap();
		try {
			String id = request.getParameter("id");
			String remarks = request.getParameter("remarks");
			if (StringUtil.isNotEmpty(id)){
				systemService.updateBySqlString("update cbs_warehouse set remarks = '"+remarks+"',is_close='1' where id = '"+id+"'");
			}
            List<CbsWarehouseSlaEntity> cbsWarehouseSlaEntityList = systemService.findHql("from CbsWarehouseSlaEntity where cbsWarehouseId.id='"+id+"'");
			List<CbsWarehouseSlaEntity> list =  new ArrayList<CbsWarehouseSlaEntity>();
			for (int i = 0;i<cbsWarehouseSlaEntityList.size();i++){
                List<CbsWarehouseSlaEntity> cbsWarehouseSlaEntity = systemService.findHql("from CbsWarehouseSlaEntity where shi = '"+cbsWarehouseSlaEntityList.get(i).getShi()+"' and cbsWarehouseId.id !='"+id+"'");
                if (cbsWarehouseSlaEntity!=null&&cbsWarehouseSlaEntity.size()>0){
                    list.addAll(cbsWarehouseSlaEntity);
                }
            }
			Object object = null;
			Object[] objs = list.toArray();
			//从大到小
			for(int i=0;i<list.size();i++) {
				for (int j = i + 1; j < list.size(); j++) {
					if (Integer.valueOf(list.get(i).getSlaType()) < Integer.valueOf(list.get(j).getSlaType())) {
						object = objs[i];
						objs[i] = objs[j];
						objs[j] = object;
					}
				}
			}
			System.out.println("objs:"+objs);
			System.out.println("object:"+ object);
			CbsWarehouseSlaEntity c = (CbsWarehouseSlaEntity) object;
			if (c!=null){
//				systemService.updateBySqlString("update cbs_warehouse_sla set is_priority = 1 where id = '"+c.getCbsWarehouseId().getId()+"'");
			}
			map.put("sta",1);
		}catch (Exception e){
			e.getMessage();
			map.put("sta",0);
		}
		ajaxJson.setAttributes(map);
		return ajaxJson;
	}
	@ResponseBody
	@RequestMapping(params = "getPersonMessage")
	public AjaxJson getPersonMessage(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
        try{
            String logistics = request.getParameter("logistics");
            String hql = "from TSDepart where departname = '"+logistics+"'";
            TSDepart tsDepart = systemService.singleResult(hql);
            List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where belongOrg.id = '" + tsDepart.getId() + "'");
            ajaxJson.setObj(zyContactsEntities);
        }catch (Exception e){
            e.getMessage();
        }
		return ajaxJson;

	}
	/**
	 * 删除物流仓库信息表
	 *
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(CbsWarehouseEntity cbsWarehouse, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		cbsWarehouse = systemService.getEntity(CbsWarehouseEntity.class, cbsWarehouse.getId());
		message = "物流仓库信息表删除成功";
		try{
			cbsWarehouseService.delete(cbsWarehouse);
			systemService.updateBySqlString("DELETE from cbs_warehouse_sla where cbs_warehouse_id = '"+cbsWarehouse.getId()+"'");
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "物流仓库信息表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除物流仓库信息表
	 *
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "物流仓库信息表删除成功";
		try{
			for(String id:ids.split(",")){
				CbsWarehouseEntity cbsWarehouse = systemService.getEntity(CbsWarehouseEntity.class,
						id
				);
				systemService.updateBySqlString("DELETE from cbs_warehouse_sla where cbs_warehouse_id = '"+cbsWarehouse.getId()+"'");
				cbsWarehouseService.delete(cbsWarehouse);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "物流仓库信息表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	/**
	 * 批量删除物流仓库信息表
	 *
	 * @return
	 */
	@RequestMapping(params = "setPriority")
	@ResponseBody
	public AjaxJson setPriority(HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		String id = request.getParameter("sid");
		Map map = new HashMap();
//		message = "设置推荐成功";
		try{
			systemService.updateBySqlString("update cbs_warehouse set is_priority = '1' where id ='"+id+"'");
			map.put("code","设置推荐成功");

		}catch(Exception e){
			e.printStackTrace();
//			message = "设置推荐失败";
			map.put("code","设置推荐失败");
			throw new BusinessException(e.getMessage());
		}
		j.setAttributes(map);
		return j;
	}
	/**
	 * 导入功能跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		return new ModelAndView("com/zybk/cbswarehouse/cbsWarehouseUpload");
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(CbsWarehouseEntity cbsWarehouse,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(CbsWarehouseEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsWarehouse, request.getParameterMap());
		List<CbsWarehouseEntity> cbsWarehouses = this.cbsWarehouseService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"物流仓库信息表");
		modelMap.put(NormalExcelConstants.CLASS,CbsWarehouseEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("物流仓库信息表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
				"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,cbsWarehouses);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(CbsWarehouseEntity cbsWarehouse,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		modelMap.put(TemplateExcelConstants.FILE_NAME, "物流仓库信息表");
		modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("Excel模板地址"));
		modelMap.put(TemplateExcelConstants.MAP_DATA,null);
		modelMap.put(TemplateExcelConstants.CLASS,CbsWarehouseEntity.class);
		modelMap.put(TemplateExcelConstants.LIST_DATA,null);
		return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<CbsWarehouseEntity> listCbsWarehouseEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(),CbsWarehouseEntity.class,params);
				for (CbsWarehouseEntity cbsWarehouse : listCbsWarehouseEntitys) {
					cbsWarehouseService.save(cbsWarehouse);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	@RequestMapping(params = "addWarouseMsg")
	public void addWarouseMsg(HttpServletRequest request) throws Exception {

		cbsWarehouseService.readFileToMsg("E:/物流SLA.xlsx");
	}
}
